<template>
  <el-form :model="formData" ref="vForm" :rules="rules" label-position="left" label-width="80px" size="default"
    @submit.prevent>
    <el-row>
      <el-col :span="3" class="grid-cell">
      </el-col>
      <el-col :span="18" class="grid-cell">
        <el-form-item label="分类" prop="categoryId" class="required label-center-align">
          <el-select v-model="formData.categoryId" placeholder="请选择分类" style="width: 200px">
            <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName"
              :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tagName" class="label-center-align">
          <div class="flex gap-2">
            <el-tag v-for="tag in formData.tagName" :key="tag" closable :disable-transitions="false"
              @close="handleClose(tag)">
              {{ tag }}
            </el-tag>
            <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
              @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
              + New Tag
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
        <VMdTextareaEditor v-model="formData.content"  height="700px" />
         
        </el-form-item>
        <el-form-item label="标题" prop="title" class="required label-center-align">
          <el-input v-model="formData.title" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="摘要" prop="summary" class="label-center-align">
          <el-input type="textarea" v-model="formData.summary" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="image" class="label-center-align">
          <el-upload :file-list="imageFileList" :headers="imageUploadHeaders" :data="imageUploadData"
            :on-success="uploadSuccess" list-type="picture-card" show-file-list :limit="1"
            :action="url"> 
            <!-- "'http://'+import.meta.env.VITE_APP_ADRESS+':'+import.meta.env.VITE_APP_PORT+'/admin/common/upload'" -->
            <template #default><i
                class="el-icon-plus"></i></template></el-upload>
        </el-form-item>
        <el-button type="primary" @click="submitcaogao">存草稿</el-button>
        <el-button @click="submitForm">发布</el-button>
      </el-col>
      <el-col :span="3" class="grid-cell">
      </el-col>
    </el-row>
  </el-form>

</template>

<script>
import {
  defineComponent,
  toRefs,
  reactive,
  getCurrentInstance,
  onBeforeUnmount, ref, shallowRef, onMounted, nextTick

}
  from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { post, category } from '@/api'
import { ElNotification } from 'element-plus'
import VMdTextareaEditor from "@kangc/v-md-editor";
export default defineComponent({
  components: { Editor, Toolbar,VMdTextareaEditor },
  props: {},
  setup() {
    const url = 'http://'+import.meta.env.VITE_APP_ADRESS+':'+import.meta.env.VITE_APP_PORT+'/admin/common/upload'
    const state = reactive({
      formData: {
        categoryId: "",
        tagName: [],
        content: "",
        title: "",
        summary: "",
        image: null,
      },
      rules: {
        categoryId: [{
          required: true,
          message: '字段值不可为空',
        }],
        content: [{
          required: true,
          message: '字段值不可为空',
        }],
        title: [{
          required: true,
          message: '字段值不可为空',
        }],
      },
      categoryIdOptions: [],
      imageFileList: [],
      imageUploadHeaders: {
        token: sessionStorage.getItem("token")
      },
      imageUploadData: {},
    })
    const inputValue = ref('')
    const inputVisible = ref(false)
    const InputRef = ref()


	//md必要参数
	const inputContent = ref('');
	const mode = ref('edit'); // 默认为编辑模式
	
	
    const handleClose = (tag) => {
      state.formData.tagName.splice(state.formData.tagName.indexOf(tag), 1)
    }
    const showInput = () => {
      // 将 inputVisible 设置为 true，使其在视图中可见
      inputVisible.value = true;
      // 使用 nextTick 等待 DOM 更新
      nextTick(() => {
        // 确保 inputRef 已经被赋值，然后获取 input 元素并调用 focus 方法
        if (InputRef.value && InputRef.value.input) {
          InputRef.value.input.focus();
        }
      });
    };
    const handleInputConfirm = () => {
      if (inputValue.value) {
        state.formData.tagName.push(inputValue.value)
      }
      inputVisible.value = false
      inputValue.value = ''
    }
    //分类列表
    const categoryList = ref([
      {
        categoryId: 1,
        categoryName: "java",
      },
      {
        categoryId: 2,
        categoryName: "python",
      },
      {
        categoryId: 3,
        categoryName: "c++",
      },
    ])
    const instance = getCurrentInstance()
    const submitForm = () => {
      instance.proxy.$refs['vForm'].validate(valid => {
        if (!valid) return
        // 表单验证通过，执行提交逻辑
        state.formData.status = 1
        post.add(state.formData).then(res => {
          ElNotification({
            title: 'Success',
            message: '发布成功',
            type: 'success',
          })
          console.log(res);
        })
      })
    }
    const submitcaogao = () => {
      instance.proxy.$refs['vForm'].validate(valid => {
        if (!valid) return
        // 表单验证通过，执行提交逻辑
        state.formData.status = 0
        post.add(state.formData).then(res => {
          ElNotification({
            title: 'Info',
            message: '已存进草稿箱',
            type: 'info',
          })
          console.log(res);
        })
      })
    }
    const resetForm = () => {
      instance.proxy.$refs['vForm'].resetFields()
    }
    const uploadSuccess = (res, file) => {
      console.log(res)
      // 'res' 是上传成功的响应数据，'file' 是文件对象
      // 假设服务器返回的响应数据中包含图片URL
      if (res.code === 200) { // 根据你的后端实际响应格式来处理

        const imageUrl = res.data; // 假设图片URL在res.data.url中
        console.log("图片上传成功，URL:", imageUrl);

        // 将图片URL添加到formData中或其他需要的地方
        state.formData.image = imageUrl;
      }
    };

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      getCategory()
      setTimeout(() => {
        state.formData.content = ''
      }, 1500)
    })

    const toolbarConfig = {}
    const editorConfig = { placeholder: '请输入内容...' }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }
    const getCategory = () => {
      category.get().then((res) => {
        categoryList.value = res.data.data
        console.log("获取分类:", res.data)
      })
    }

    return {
      ...toRefs(state),
      inputValue,
      inputVisible,
      InputRef,
      handleClose,
      showInput,
      handleInputConfirm, // 如果这是你需要在模板中使用的方法
      submitForm,
      resetForm,
      uploadSuccess,
      editorRef,
      toolbarConfig,
      editorConfig,
      handleCreated,
      categoryList,
      url
    }
  }
})

</script>

<style lang="scss">
.el-input-number.full-width-input,
.el-cascader.full-width-input {
  width: 100% !important;
}

.el-form-item--medium {
  .el-radio {
    line-height: 36px !important;
  }

  .el-rate {
    margin-top: 8px;
  }
}

.el-form-item--small {
  .el-radio {
    line-height: 32px !important;
  }

  .el-rate {
    margin-top: 6px;
  }
}

.el-form-item--mini {
  .el-radio {
    line-height: 28px !important;
  }

  .el-rate {
    margin-top: 4px;
  }
}

.clear-fix:before,
.clear-fix:after {
  display: table;
  content: "";
}

.clear-fix:after {
  clear: both;
}

.float-right {
  float: right;
}
</style>

<style lang="scss" scoped>
div.table-container {
  table.table-layout {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;

    td.table-cell {
      display: table-cell;
      height: 36px;
      border: 1px solid #e1e2e3;
    }
  }
}

.label-left-align :deep(.el-form-item__label) {
  text-align: left;
}

.label-center-align :deep(.el-form-item__label) {
  text-align: center;
}

.label-right-align :deep(.el-form-item__label) {
  text-align: right;
}

.static-content-item {
  min-height: 20px;
  display: flex;
  align-items: center;

  :deep(.el-divider--horizontal) {
    margin: 0;
  }
}
</style>